package net.suncaper.psychological.web.controller;

import net.suncaper.psychological.common.framework.simplemvc.RequestMapping;
import net.suncaper.psychological.common.utils.Result;
import net.suncaper.psychological.common.utils.MyDbUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 值班安排控制器
 */
@RequestMapping("/api/duty")
public class DutyScheduleController {

    @RequestMapping("/list.do")
    public void getDutyList(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取查询参数
            String startDate = request.getParameter("startDate");
            String endDate = request.getParameter("endDate");
            
            String sql;
            List<Map<String, Object>> duties;
            
            if (startDate != null && endDate != null) {
                // 按日期范围查询
                sql = "SELECT d.*, u.name as teacher_name, u.extra_info " +
                      "FROM duty_schedule d " +
                      "LEFT JOIN user u ON d.user_id = u.id " +
                      "WHERE DATE(d.start_time) BETWEEN ? AND ? " +
                      "ORDER BY d.start_time";
                duties = MyDbUtil.executeQueryMap(sql, startDate, endDate);
            } else {
                // 查询所有值班安排
                sql = "SELECT d.*, u.name as teacher_name, u.extra_info " +
                      "FROM duty_schedule d " +
                      "LEFT JOIN user u ON d.user_id = u.id " +
                      "ORDER BY d.start_time";
                duties = MyDbUtil.executeQueryMap(sql);
            }
            
            // 处理额外信息
            for (Map<String, Object> duty : duties) {
                String extraInfo = (String) duty.get("extra_info");
                if (extraInfo != null && !extraInfo.isEmpty()) {
                    try {
                        Map<String, Object> extra = JSON.parseObject(extraInfo, Map.class);
                        duty.put("teacher_avatar", extra.get("avatar"));
                        duty.put("teacher_title", extra.get("title"));
                    } catch (Exception e) {
                        System.err.println("解析用户额外信息失败: " + e.getMessage());
                    }
                }
            }
            
            Result.success(duties).writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("获取值班列表失败: " + e.getMessage()).writeTo(response);
        }
    }

    @RequestMapping("/add.do")
    public void addDuty(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            String jsonData = getRequestBody(request);
            System.out.println("收到添加值班请求数据: " + jsonData);
            
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            
            String sql = "INSERT INTO duty_schedule(user_id, role, start_time, end_time, location) VALUES (?, ?, ?, ?, ?)";
            
            int result = MyDbUtil.executeUpdate(sql, 
                data.get("user_id"),
                data.get("role"),
                data.get("start_time"),
                data.get("end_time"),
                data.get("location")
            );
            
            response.setContentType("application/json;charset=UTF-8");
            if (result > 0) {
                String jsonResponse = "{\"code\":200,\"success\":true,\"data\":\"值班安排添加成功\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("添加成功，返回: " + jsonResponse);
            } else {
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"值班安排添加失败\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("添加失败，返回: " + jsonResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"添加值班安排时发生错误: " + e.getMessage().replace("\"", "\\\"") + "\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("异常，返回: " + jsonResponse);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @RequestMapping("/update.do")
    public void updateDuty(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            String jsonData = getRequestBody(request);
            System.out.println("收到更新值班请求数据: " + jsonData);
            
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            
            String sql = "UPDATE duty_schedule SET user_id=?, role=?, start_time=?, end_time=?, location=? WHERE id=?";
            
            int result = MyDbUtil.executeUpdate(sql, 
                data.get("user_id"),
                data.get("role"),
                data.get("start_time"),
                data.get("end_time"),
                data.get("location"),
                data.get("id")
            );
            
            response.setContentType("application/json;charset=UTF-8");
            if (result > 0) {
                String jsonResponse = "{\"code\":200,\"success\":true,\"data\":\"值班安排更新成功\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("更新成功，返回: " + jsonResponse);
            } else {
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"值班安排更新失败\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("更新失败，返回: " + jsonResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"更新值班安排时发生错误: " + e.getMessage().replace("\"", "\\\"") + "\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("异常，返回: " + jsonResponse);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @RequestMapping("/delete.do")
    public void deleteDuty(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            String jsonData = getRequestBody(request);
            System.out.println("收到删除值班请求数据: " + jsonData);
            
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            Long id = Long.valueOf(data.get("id").toString());
            
            String sql = "DELETE FROM duty_schedule WHERE id = ?";
            int result = MyDbUtil.executeUpdate(sql, id);
            
            response.setContentType("application/json;charset=UTF-8");
            if (result > 0) {
                String jsonResponse = "{\"code\":200,\"success\":true,\"data\":\"值班安排删除成功\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("删除成功，返回: " + jsonResponse);
            } else {
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"值班安排删除失败\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("删除失败，返回: " + jsonResponse);
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"删除值班安排时发生错误: " + e.getMessage().replace("\"", "\\\"") + "\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("异常，返回: " + jsonResponse);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @RequestMapping("/batch-add.do")
    public void batchAddDuty(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            
            String jsonData = getRequestBody(request);
            System.out.println("收到批量添加值班请求数据: " + jsonData);
            
            @SuppressWarnings("unchecked")
            List<Map> rawDataList = JSON.parseArray(jsonData, Map.class);
            List<Map<String, Object>> dataList = new ArrayList<>();
            for (Map rawMap : rawDataList) {
                dataList.add((Map<String, Object>) rawMap);
            }
            
            int successCount = 0;
            String sql = "INSERT INTO duty_schedule(user_id, role, start_time, end_time, location) VALUES (?, ?, ?, ?, ?)";
            
            for (Map<String, Object> data : dataList) {
                try {
                    int result = MyDbUtil.executeUpdate(sql, 
                        data.get("user_id"),
                        data.get("role"),
                        data.get("start_time"),
                        data.get("end_time"),
                        data.get("location")
                    );
                    if (result > 0) {
                        successCount++;
                    }
                } catch (Exception e) {
                    System.err.println("批量添加单条记录失败: " + e.getMessage());
                }
            }
            
            response.setContentType("application/json;charset=UTF-8");
            String jsonResponse = "{\"code\":200,\"success\":true,\"data\":\"批量添加完成，成功添加 " + successCount + " 条记录\"}";
            response.getWriter().write(jsonResponse);
            System.out.println("批量添加完成，返回: " + jsonResponse);
            
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json;charset=UTF-8");
                String jsonResponse = "{\"code\":500,\"success\":false,\"message\":\"批量添加值班安排时发生错误: " + e.getMessage().replace("\"", "\\\"") + "\"}";
                response.getWriter().write(jsonResponse);
                System.out.println("异常，返回: " + jsonResponse);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    // 新增：获取指定时间段内的值班安排（用于咨询师选择）
    @RequestMapping("/available")
    public void getAvailableDutySchedules(HttpServletRequest request, HttpServletResponse response) {
        try {
            String appointmentTime = request.getParameter("appointmentTime");
            String role = request.getParameter("role"); // 固定为 CONSULTANT
            
            System.out.println("查询咨询师值班安排参数 - appointmentTime: " + appointmentTime + ", role: " + role);
            
            if (appointmentTime == null) {
                Result.error("预约时间不能为空").writeTo(response);
                return;
            }
            
            // 只查询咨询师的值班安排，预约时间在值班时间范围内
            String sql = "SELECT ds.*, u.name as consultant_name, u.phone as consultant_phone " +
                        "FROM duty_schedule ds " +
                        "LEFT JOIN user u ON ds.user_id = u.id " +
                        "WHERE ds.role = 'CONSULTANT' " +
                        "AND ds.start_time <= ? " +
                        "AND ds.end_time >= ? " +
                        "ORDER BY ds.start_time";
            
            List<Map<String, Object>> schedules = MyDbUtil.executeQueryMap(sql, appointmentTime, appointmentTime);
            
            System.out.println("查询到咨询师值班安排数量: " + schedules.size());
            for (Map<String, Object> schedule : schedules) {
                System.out.println("咨询师值班安排: " + schedule.get("consultant_name") + " - " + 
                                 schedule.get("start_time") + " 到 " + schedule.get("end_time"));
            }
            
            Result.success(schedules, "查询咨询师值班安排成功").writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("查询咨询师值班安排异常: " + e.getMessage()).writeTo(response);
        }
    }

    // 新增：获取所有咨询师的值班安排
    @RequestMapping("/consultants")
    public void getConsultantDutySchedules(HttpServletRequest request, HttpServletResponse response) {
        try {
            String sql = "SELECT ds.*, u.name as consultant_name, u.phone as consultant_phone, " +
                        "u.extra_info " +
                        "FROM duty_schedule ds " +
                        "LEFT JOIN user u ON ds.user_id = u.id " +
                        "WHERE ds.role = 'CONSULTANT' " +
                        "AND ds.start_time >= NOW() " +
                        "ORDER BY ds.start_time";
            
            List<Map<String, Object>> schedules = MyDbUtil.executeQueryMap(sql);
            
            // 处理extra_info字段，提取咨询师的专业信息
            for (Map<String, Object> schedule : schedules) {
                Object extraInfo = schedule.get("extra_info");
                if (extraInfo != null) {
                    try {
                        // 这里可以解析JSON获取咨询师的专业信息
                        // 暂时保持原样
                    } catch (Exception e) {
                        // 如果解析失败，忽略
                    }
                }
            }
            
            Result.success(schedules, "查询咨询师值班安排成功").writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("查询咨询师值班安排异常: " + e.getMessage()).writeTo(response);
        }
    }

    // 新增：获取指定日期的值班安排
    @RequestMapping("/by-date")
    public void getDutySchedulesByDate(HttpServletRequest request, HttpServletResponse response) {
        try {
            String date = request.getParameter("date");
            String role = request.getParameter("role");
            
            if (date == null) {
                Result.error("日期不能为空").writeTo(response);
                return;
            }
            
            String sql;
            List<Map<String, Object>> schedules;
            
            if (role != null && !role.trim().isEmpty()) {
                sql = "SELECT ds.*, u.name as consultant_name, u.phone as consultant_phone " +
                      "FROM duty_schedule ds " +
                      "LEFT JOIN user u ON ds.user_id = u.id " +
                      "WHERE ds.role = ? " +
                      "AND DATE(ds.start_time) = ? " +
                      "ORDER BY ds.start_time";
                schedules = MyDbUtil.executeQueryMap(sql, role, date);
            } else {
                sql = "SELECT ds.*, u.name as consultant_name, u.phone as consultant_phone " +
                      "FROM duty_schedule ds " +
                      "LEFT JOIN user u ON ds.user_id = u.id " +
                      "WHERE DATE(ds.start_time) = ? " +
                      "ORDER BY ds.start_time";
                schedules = MyDbUtil.executeQueryMap(sql, date);
            }
            
            Result.success(schedules, "查询值班安排成功").writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("查询值班安排异常: " + e.getMessage()).writeTo(response);
        }
    }

    /**
     * 读取请求体中的JSON数据
     */
    private String getRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString();
    }
} 